//
//  GQJTextView.m
//  TotalDemo
//
//  Created by gujian on 16/5/24.
//  Copyright © 2016年 gujian. All rights reserved.
//

#import "GQJTextView.h"

const CGFloat kFontSize = 15.0;
NSString * const kPlaceHolder = @"请输入文字";
const NSInteger kMinHeight = 34;
const NSInteger kMaxHeight = 52;

@interface GQJTextView()<UITextViewDelegate>

@property (nonatomic, weak) UILabel *placeHolderLbl;
@property (nonatomic, weak) UITextView *textView;

@end

@implementation GQJTextView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self initSubViews];
    }
    
    return self;
}


- (void)initSubViews
{
    CGSize size = self.frame.size;
    CGFloat lblHeight = [kPlaceHolder sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kFontSize]}].height;
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(5, 7, size.width, lblHeight)];
    lbl.text = kPlaceHolder;
    lbl.textColor = [UIColor lightGrayColor];
    lbl.font = [UIFont systemFontOfSize:kFontSize];
    [self addSubview:lbl];
    _placeHolderLbl = lbl;
    
    UITextView *textView = [[UITextView alloc] initWithFrame:self.bounds];
    textView.scrollEnabled = NO;
    textView.showsHorizontalScrollIndicator = NO;
    textView.contentInset = UIEdgeInsetsZero;
    textView.textColor = [UIColor blackColor];
    textView.delegate = self;
    textView.contentMode = UIViewContentModeRedraw;
    textView.font = [UIFont systemFontOfSize:kFontSize];
    [self addSubview:textView];
    _textView = textView;
    
    [self bringSubviewToFront:_placeHolderLbl];

}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGSize size = self.frame.size;
    CGFloat lblHeight = [_placeHolderLbl.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kFontSize]}].height;
    _placeHolderLbl.frame = CGRectMake(5, 7, size.width, lblHeight);
    
    CGRect frame = self.bounds;
    frame.origin.y = 0;
    frame.origin.x = 0;
    _textView.frame = frame;
}

#pragma mark - UITextView delegate

- (void)textViewDidChange:(UITextView *)textView
{
    _placeHolderLbl.hidden = textView.text.length>0;
    
    //跳转frame大小
    [self resizeTextView:textView];
    
}

- (void)resizeTextView:(UITextView *)textView
{
    NSInteger realHeight = [self calculateHeight];
    
    if (realHeight < kMinHeight || !textView.hasText)
    {
        realHeight = kMinHeight;
    }else if(kMaxHeight && realHeight > kMaxHeight)
    {
        realHeight = kMaxHeight;
    }
    
    if(textView.frame.size.height != realHeight)
    {
        if (realHeight >= kMaxHeight)
        {
            if (!self.textView.scrollEnabled) {
                self.textView.scrollEnabled = YES;
                [self.textView flashScrollIndicators];
            }
            
        }
        else
        {
            self.textView.scrollEnabled = NO;
        }
        
        
        if (realHeight <= kMaxHeight) {
            [UIView animateWithDuration:0.1 animations:^{
                CGRect frame = self.frame;
                frame.size.height = realHeight;
                self.frame = frame;
                frame.origin.y = 0;
                frame.origin.x = 0;
                if (!CGRectEqualToRect(frame, self.textView.frame)) {
                    self.textView.frame = frame;
                }
                
            } completion:^(BOOL finished) {
                
            }];
        }
    }

    //tag
    
    [self performSelector:@selector(resetScrollPosition) withObject:nil afterDelay:0.1];
    
    [self resetScrollPosition];
    
}

- (CGFloat)calculateHeight
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        return ceil([self.textView sizeThatFits:self.textView.frame.size].height);
    }else
        return self.textView.contentSize.height;
}

- (void)resetScrollPosition
{
     if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        CGRect r = [self.textView caretRectForPosition:self.textView.selectedTextRange.end];
        CGFloat caretY =  MAX(r.origin.y - self.textView.frame.size.height + r.size.height + 8, 0);
         if (self.textView.contentOffset.y < caretY && r.origin.y != INFINITY){
//            self.textView.contentOffset = CGPointMake(0, caretY);
             
             //无法激发系统方法adjustShadowsIfNecessary
             CGPoint s = CGPointMake(0, caretY);
             if (s.y > self.textView.contentSize.height - self.textView.frame.size.height && !self.textView.decelerating && !self.textView.tracking && !self.textView.dragging)
                 s = CGPointMake(s.x, self.textView.contentSize.height - self.textView.frame.size.height);
             self.textView.contentOffset = s;

         }
         

     }
}

@end
